package com.shujia.zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ZKAPITest {
    ZooKeeper zk = null;

    @Before
    public void conn() throws IOException {
        zk = new ZooKeeper("master:2181,node1:2181,node2:2181", 30000, null);
    }

    @Test
    // 在zk上创建节点 并保存数据
    // ZooDefs.Ids.OPEN_ACL_UNSAFE : 不做任何权限认证
    // CreateMode.PERSISTENT 创建永久节点
    // CreateMode.EPHEMERAL 创建临时节点，连接断开自动删除
    public void createZNode() throws InterruptedException, KeeperException {
        zk.create("/test1",
                "data1".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
    }

    @Test
    public void createTempZNode() throws InterruptedException, KeeperException {
        zk.create("/test3",
                "data1".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);

    }

    @Test
    public void watchEvent() {
        try {
            // 非阻塞地监听/test1的变化
            // 可以监听
            zk.exists("/test1", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println(event);
                    System.out.println("/test1有变化");
                }
            });
            while (true) {

            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @After
    public void close() {
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
